import { App, Button, DatePicker, Descriptions, Dropdown, Flex, Form, Input, InputNumber, Modal, Select, Space, Table, Tag, Upload } from "antd";
import { useContext, useEffect, useState } from "react";
import { useForm } from "antd/es/form/Form";
import Search from "antd/es/input/Search";
import { material_api } from "../api/materials";
import { project_api } from "../api/projects";
import { provider_api } from "../api/providers";
import { contract_api } from "../api/conracts";
import dayjs from "dayjs";
import { MinusCircleOutlined, PlusOutlined, UploadOutlined } from "@ant-design/icons";
import { api_urls } from "../api/urls";
import storage from "../storage";
import { Global } from "../main";
import { USER_ROLE } from "../api/users";



export function Material() {
    const [searchLoading, setSearchLoading] = useState(false)
    const [materialPage, setMaterialPage] = useState({ total: 0, content: [] })
    const [materialReq, setMaterialReq] = useState({ keyword: '', page: 1, size: 15, contract_id: -1 })
    const [updateMaterialModalOpen, setMaterialProjectModalOpen] = useState(false)
    const [createMaterialModalOpen, setCreateMaterialModalOpen] = useState(false)
    const [verifyAmountModalOpen, setVerifyAmountModalOpen] = useState(false)
    const [createMaterialForm] = useForm();
    const [updateMaterialForm] = useForm();
    const [verifyAmountMaterialForm] = useForm();
    const { message, modal } = App.useApp();
    const [currentMaterial, setCurrentMaterial] = useState(null);

    const [allContracts, setAllContracts] = useState([]);
    const [contracts, setContracts] = useState([]);
    const [contractsForAdd, setcontractsForAdd] = useState([]);
    const [selectedContract, setSelectedContract] = useState(-1);

    const [uploadLoading, setUploadLoading] = useState(false);
    const { role } = useContext(Global)
    const columns = [
        // {
        //     title: '项目',
        //     dataIndex: 'project_name',
        //     key: 'project_name',
        // },
        // {
        //     title: '供应商',
        //     dataIndex: 'provider_name',
        //     key: 'provider_name',
        // },
        {
            title: '合同编号',
            dataIndex: 'contract_no',
            key: 'contract_no',
        },
        {
            title: '送货日期',
            key: 'delivery_date',
            render: (_, row) => (
                row.delivery_date ? dayjs(row.delivery_date).format("YYYY-MM-DD") : ''
            )
        },
        {
            title: '产品单号',
            key: 'delivery_numer',
            dataIndex: 'delivery_numer',
        },
        {
            title: '所属公司',
            key: 'affiliation',
            dataIndex: 'affiliation',
        },
        {
            title: '类别',
            key: 'category',
            dataIndex: 'category',
        },
        {
            title: '名称',
            key: 'name',
            dataIndex: 'name',
        },
        {
            title: '规格',
            key: 'specification',
            dataIndex: 'specification',
        },
        {
            title: '单位',
            key: 'unit',
            dataIndex: 'unit',
        },
        {
            title: '核对数量',
            key: 'verify_number',
            dataIndex: 'verify_number',
        },
        {
            title: '单价',
            key: 'price',
            dataIndex: 'price',
        },
        {
            title: '核对金额',
            key: 'verify_amount',
            render: (_, row) => (<>
                {`${row.verify_amount}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
            </>)
        },
        {
            title: '历史欠款',
            key: 'his_defaulters_amount',
            render: (_, row) => (<>
                {`${row.his_defaulters_amount}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
            </>)
        },
        {
            title: '历史挂票',
            key: 'his_defaulters_amount',
            render: (_, row) => (<>
                {`${row.his_defaulters_amount}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
            </>)
        },
        {
            title: '备注',
            key: 'comment',
            dataIndex: 'comment',
        },
        Table.EXPAND_COLUMN,
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 150,
            render: (_, row) => (<Space size={'middle'}>
                <Dropdown.Button type="link"
                    onClick={() => {
                        verifyAmountMaterialForm.setFieldsValue({ ...row, delivery_date: dayjs(row.delivery_date, 'YYYY-MM-DD') });
                        setCurrentMaterial(row);
                        setVerifyAmountModalOpen(true)
                    }}
                    menu={{
                        items: [{
                            key: 'update',
                            label: '编辑'
                        }, {
                            key: 'delete',
                            label: '删除'
                        }],
                        onClick: (e) => {
                            if (e.key === 'update') {
                                updateMaterialForm.setFieldsValue({ ...row, delivery_date: dayjs(row.delivery_date) });
                                setCurrentMaterial(row);
                                setMaterialProjectModalOpen(true)
                            } else if (e.key === 'delete') {
                                modal.confirm({
                                    title: "删除供货记录",
                                    content: `确认要删除供货记录吗？`,
                                    onOk: () => {
                                        material_api.deleteMaterial(row.id).then(() => {
                                            reFreshMaterial();
                                        }).catch(e => message.error(e))
                                    },
                                    okText: '确定',
                                    cancelText: '取消'
                                })
                            }
                        },
                    }}
                    disabled={role === USER_ROLE.READONLY}
                >
                    {row.verifyAmount === '' ? '核对金额' : '重新核对'}
                </Dropdown.Button>
            </Space>)
        },
    ];
    const reFreshMaterial = (ur) => {
        let request = materialReq;
        if (!!ur) {
            request = ur;
        }
        material_api.pageMaterial(request).then(data => {
            let content = data.content.map(it => {
                const columns = material_api.handleExtraColumns(it[0]);
                return { ...it[0], key: it[0].id, contract_no: it[1].no, exts: columns }
            })

            setMaterialPage({ total: data.total, content: content })
            setSearchLoading(false)
        }).catch(e => message.error(e))
    }

    useEffect(() => {

        contract_api.pageContract({ keyword: '', page: 1, size: -1, project_id: -1, provider_id: -1 }).then(contracts => {
            setAllContracts(contracts.content.map(it => ({ label: it.no, value: it.id })))
            setContracts(contracts.content.map(it => ({ label: it.no, value: it.id })))
            setcontractsForAdd(contracts.content.map(it => ({ label: it.no, value: it.id })))
        })
        reFreshMaterial()
    }, []);
    return <>
        <Space style={{ margin: '10px' }}>
            <Select size="large" style={{ width: '15vw' }} value={selectedContract} defaultValue={-1}
                showSearch
                filterOption={(input, option) => {
                    return (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                }}
                title="选择合同" options={[{ value: -1, label: '所有合同' }, ...contracts]}
                onChange={(value) => { setSelectedContract(value) }}></Select>
            <Search size="large" placeholder="输入名称进行搜素" style={{ maxWidth: '30vw' }} loading={searchLoading}
                onSearch={(value) => {
                    setSearchLoading(true)
                    setMaterialReq({ ...materialReq, keyword: value, contract_id: selectedContract })
                    reFreshMaterial({ ...materialReq, keyword: value, contract_id: selectedContract })
                }}></Search>
            <Upload name="file" action={api_urls.material.upload} showUploadList={false} loading={uploadLoading} headers={{
                token: storage.getUser()?.token
            }}
                beforeUpload={(file) => {
                    const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                    if (!isExcel) {
                        message.error(`只能导入excel文件!`);
                    }
                    return isExcel || Upload.LIST_IGNORE;
                }}
                onChange={info => {
                    if (info.file.status !== 'uploading') {
                        setUploadLoading(true)
                    }
                    if (info.file.status === 'done') {
                        setUploadLoading(false)
                        message.success(`导入成功`);
                        reFreshMaterial({ ...materialReq })
                    } else if (info.file.status === 'error') {
                        setUploadLoading(false)
                        message.error(`导入失败`);
                    }
                }}>
                <Button disabled={role === USER_ROLE.READONLY} type="primary" size="large" icon={<UploadOutlined></UploadOutlined>}>导入</Button>
            </Upload>
            <Button disabled={role === USER_ROLE.READONLY} size="large" type="primary" onClick={() => {
                setCurrentMaterial(null)
                createMaterialForm.setFieldsValue(null)
                createMaterialForm.resetFields();
                setCreateMaterialModalOpen(true)
            }}>创建</Button>
            <a size="large" type="link" href="/material_template.xlsx">下载模板文件</a>
        </Space>
        <Table size="small" pagination={{
            position: ["bottomLeft"],
            pageSizeOptions: [materialReq.size],
            total: materialPage.total,
            current: materialReq.page,
            pageSize: materialReq.size,
            onChange: (page, pageSize) => {
                setMaterialReq({ ...materialReq, page: page, size: pageSize });
                reFreshMaterial({ ...materialReq, page: page, size: pageSize })

            }
        }} dataSource={materialPage.content} columns={columns}
            expandable={{
                expandedRowRender: (row) => <Descriptions title="附加信息" items={row.exts.map(it => ({
                    key: it.id,
                    label: it.ext_name,
                    children: it.ext_value
                }))} />,
                rowExpandable: (row) => row.exts && row.exts.length > 0
            }}></Table>
        <Modal maskClosable={false} title="编辑材料记录" okText="确定" cancelText="取消" onOk={() => {
            updateMaterialForm.validateFields().then(data => {
                material_api.updateMaterial({ ...data, delivery_date: data.delivery_date.valueOf() }).then(() => {
                    reFreshMaterial();
                    setMaterialProjectModalOpen(false)
                }).catch(e => message.error(e.response.data || ""))
            });

        }} onCancel={() => setMaterialProjectModalOpen(false)} open={updateMaterialModalOpen}>
            <Form labelCol={{ span: 6 }} value={currentMaterial} wrapperCol={{ span: 18 }} form={updateMaterialForm} initialValues={currentMaterial}>
                <Form.Item label="索引" name={"id"} hidden>
                    <Input />
                </Form.Item>
                <Form.Item label="合同编号" name={"contract_id"} rules={[{
                    required: true,
                    message: '请选择合同'
                }]}>
                    <Select disabled options={contractsForAdd} showSearch filterOption={(input, option) => {
                        return (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }}></Select>
                </Form.Item>
                <Form.Item label="送货日期" name={"delivery_date"} rules={[{ required: true }]}>
                    <DatePicker></DatePicker>
                </Form.Item>
                <Form.Item label="产品单号" name={"delivery_numer"} rules={[{ required: true }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="所属公司" name={"affiliation"} rules={[{ required: true }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="类别" name={"category"} rules={[{ required: true }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="名称" name={"name"} rules={[{ required: true }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="规格" name={"specification"} rules={[{ required: true }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="单位" name={"unit"} rules={[{ required: true }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="核对数量" name={"verify_number"} rules={[{ required: true }]}>
                    <InputNumber precision={2} style={{ width: '100%' }} />
                </Form.Item>
                <Form.Item label="单价" name={"price"} rules={[{ required: true }]}>
                    <InputNumber precision={2} style={{ width: '100%' }} />
                </Form.Item>
                <Form.Item label="核对金额" name={"verify_amount"} rules={[{ required: true, message: '请输入核对金额' }]}>
                    <InputNumber precision={2} formatter={(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                        parser={(value) => value.replace(/\$\s?|(,*)/g, '')} style={{ width: '100%' }} />
                </Form.Item>
                <Form.Item label="备注" name={"comment"}>
                    <Input />
                </Form.Item>
                <Form.List name={"exts"} rules={[
                    {
                        validator: async (_, exts) => {
                            if (!exts || exts.length > 20) {
                                return Promise.reject(new Error('最大支持20个扩展字段！'));
                            }
                        },
                    },
                ]}>
                    {(fields, { add, remove }) => (
                        <>
                            {fields.map(({ key, name, ...restField }) => (
                                <Space
                                    key={key}
                                    style={{
                                        display: 'flex',
                                        marginBottom: 8,
                                    }}
                                    align="baseline"
                                >
                                    <Form.Item
                                        {...restField}
                                        label={"扩展名"}
                                        name={[name, 'ext_name']}
                                        rules={[
                                            {
                                                required: true,
                                                message: '输入字段名称',
                                            },
                                        ]}
                                    >
                                        <Input placeholder="字段名称" />
                                    </Form.Item>
                                    <Form.Item
                                        {...restField}
                                        label={"内容"}
                                        name={[name, 'ext_value']}
                                        rules={[
                                            {
                                                required: true,
                                                message: '输入字段值',
                                            },
                                        ]}
                                    >
                                        <Input placeholder="字段值" />
                                    </Form.Item>
                                    <MinusCircleOutlined onClick={() => remove(name)} />
                                </Space>
                            ))}
                            <Form.Item>
                                <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                                    添加扩展字段
                                </Button>
                            </Form.Item>
                        </>
                    )}
                </Form.List>
            </Form>
        </Modal>
        <Modal maskClosable={false} title="新建材料记录" okText="确定" cancelText="取消" onOk={() => {
            createMaterialForm.validateFields().then(data => {
                material_api.createMaterial({ ...data, delivery_date: data.delivery_date.valueOf() }).then(() => {
                    reFreshMaterial();
                    setCreateMaterialModalOpen(false)
                }).catch(e => message.error(e.response.data || ""))
            }).catch(e => {
                console.log(e)
                message.error(e.errorFields[0].errors[0])
            });

        }} onCancel={() => setCreateMaterialModalOpen(false)} open={createMaterialModalOpen}>
            <Form labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} form={createMaterialForm} initialValues={currentMaterial}>
                <Form.Item label="合同编号" name={"contract_id"} rules={[{
                    required: true,
                    message: '请选择合同'
                }]}>
                    <Select options={contractsForAdd} showSearch filterOption={(input, option) => {
                        return (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }}></Select>
                </Form.Item>
                <Form.Item label="送货日期" name={"delivery_date"} rules={[{ required: true }]}>
                    <DatePicker></DatePicker>
                </Form.Item>
                <Form.Item label="产品单号" name={"delivery_numer"} rules={[{ required: true }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="所属公司" name={"affiliation"} rules={[{ required: true }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="类别" name={"category"} rules={[{ required: true }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="名称" name={"name"} rules={[{ required: true }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="规格" name={"specification"} rules={[{ required: true }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="单位" name={"unit"} rules={[{ required: true }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="核对数量" name={"verify_number"} rules={[{ required: true }]}>
                    <InputNumber precision={2} style={{ width: '100%' }} />
                </Form.Item>
                <Form.Item label="单价" name={"price"} rules={[{ required: true }]}>
                    <InputNumber precision={2} style={{ width: '100%' }} />
                </Form.Item>
                <Form.Item label="核对金额" name={"verify_amount"} rules={[{ required: true, message: '请输入核对金额' }]}>
                    <InputNumber precision={2} formatter={(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                        parser={(value) => value.replace(/\$\s?|(,*)/g, '')} style={{ width: '100%' }} />
                </Form.Item>
                <Form.Item label="备注" name={"comment"}>
                    <Input />
                </Form.Item>
                <Form.List name={"exts"} rules={[
                    {
                        validator: async (_, exts) => {
                            if (exts === undefined) {
                                return Promise.resolve();
                            }
                            if (exts.length > 20) {
                                return Promise.reject(new Error('最大支持20个扩展字段！'));
                            }
                        },
                    },
                ]}>
                    {(fields, { add, remove }) => (
                        <>
                            {fields.map(({ key, name, ...restField }) => (
                                <Space
                                    key={key}
                                    style={{
                                        display: 'flex',
                                        marginBottom: 8,
                                    }}
                                    align="baseline"
                                >
                                    <Form.Item
                                        {...restField}
                                        label={"扩展名"}
                                        name={[name, 'ext_name']}
                                        rules={[
                                            {
                                                required: true,
                                                message: '输入字段名称',
                                            },
                                        ]}
                                    >
                                        <Input placeholder="字段名称" />
                                    </Form.Item>
                                    <Form.Item
                                        {...restField}
                                        label={"内容"}
                                        name={[name, 'ext_value']}
                                        rules={[
                                            {
                                                required: true,
                                                message: '输入字段值',
                                            },
                                        ]}
                                    >
                                        <Input placeholder="字段值" />
                                    </Form.Item>
                                    <MinusCircleOutlined onClick={() => remove(name)} />
                                </Space>
                            ))}
                            <Form.Item>
                                <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                                    添加扩展字段
                                </Button>
                            </Form.Item>
                        </>
                    )}
                </Form.List>
            </Form>
        </Modal>

        <Modal maskClosable={false} title="核对金额" okText="确定" cancelText="取消" onOk={() => {
            verifyAmountMaterialForm.validateFields().then(data => {
                material_api.verifyAmount({ id: data.id, verify_amount: data.verify_amount }).then(() => {
                    reFreshMaterial();
                    setVerifyAmountModalOpen(false)
                })
            });

        }} onCancel={() => setVerifyAmountModalOpen(false)} open={verifyAmountModalOpen}>
            <Form labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} form={verifyAmountMaterialForm} initialValues={currentMaterial}>
                <Form.Item label="索引" name={"id"} hidden>
                    <Input />
                </Form.Item>
                <Form.Item label="核对金额" name={"verify_amount"} rules={[{ required: true, message: '请输入核对金额' }]}>
                    <InputNumber precision={2} style={{ width: '100%' }} formatter={(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                        parser={(value) => value.replace(/\$\s?|(,*)/g, '')} />
                </Form.Item>
            </Form>
        </Modal>
    </>
}